package com.bluefox.hospital.service.impl;

import com.bluefox.common.web.exception.CustomRuntimeException;
import com.bluefox.hospital.model.Announcement;
import com.bluefox.hospital.repository.AnnouncementRepository;
import com.bluefox.hospital.service.AnnouncementService;
import com.bluefox.uac.security.CustomAuthenticationToken;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * AnnouncementService 实现类
 * @author Administrator
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AnnouncementServiceImpl implements AnnouncementService {

    @Autowired
    private AnnouncementRepository announcementRepository;

    @Override
    @Transactional(readOnly = true)
    public Announcement get(@NonNull Long id) {
        final  Announcement model = announcementRepository.findById(id).get();
        if (model == null) {
            throw new CustomRuntimeException("404", String.format("查找的资源[%s]不存在.", id));
        }
        return model;
    }

    @Override
    public Announcement create(Announcement model) {
        // TODO: 业务逻辑
        return announcementRepository.save(model);
    }

    @Override
    public Announcement update(Announcement model) {
        // TODO: 业务逻辑
        return announcementRepository.save(model);
    }

    @Override
    public void delete(@NonNull Long id) {
        // TODO: 业务逻辑
        announcementRepository.deleteById(id);
    }

    @Override
    @Transactional(readOnly = true)
    public Page<Announcement> findAllWeb(Pageable pageable) {
        return announcementRepository.findAll(pageable);
    }

    @Override
    @Transactional(readOnly = true)
    public Page<Announcement> findAllWeb(String type, Pageable pageable) {
        Page<Announcement> richTexts = null;
        if ("".equals(type) || null == type) {

            richTexts = announcementRepository.findAll(pageable);
        } else {
            richTexts = announcementRepository.findByType(type, pageable);
        }
        //去除大字段
        richTexts.getContent().forEach(richText -> {
            richText.setContent("");
        });
        return richTexts;
    }



    @Override
    @Transactional(readOnly = true)
    public Page<Announcement> findAll(Pageable pageable) {
        // 从springSecurity中获取登录用户
        String username = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof CustomAuthenticationToken) {
            CustomAuthenticationToken token = (CustomAuthenticationToken) authentication;
            username = token.getDetails().getUsername();
        }


        Page<Announcement> richTexts = null;

        if (StringUtils.isEmpty(username)) {
            throw new CustomRuntimeException("401", "用户未通过认证，请重新登录");
        } else if ("admin".equals(username)||"ADMIN".equals(username)) {
            richTexts = announcementRepository.findByStatus(0,pageable);
        } else {
            richTexts = announcementRepository.findByCreatedBy(username, pageable);
        }
        if (richTexts.getSize() <= 0) {
            return richTexts;
        } else {
            //去除大字段
            richTexts.getContent().forEach(richText -> {
                richText.setContent("");
            });
        }
        return richTexts;
    }

    @Override
    public Page<Announcement> findAll(String type, Pageable pageable) {
        CustomAuthenticationToken token = (CustomAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        String username = token.getDetails().getUsername();

        Page<Announcement> richTexts = null;

        if (StringUtils.isEmpty(username)) {
            throw new CustomRuntimeException("401", "用户未通过认证，请重新登录");
            // 判断用户是否登录
        } else if ("admin".equals(username)||"ADMIN".equals(username)) {
            if ("".equals(type) || null == type) {
                richTexts = announcementRepository.findAll( pageable);
            } else {
                richTexts = announcementRepository.findByTypeAndStatus(type,1,pageable);
            }
        }else{
            if ("".equals(type) || null == type) {
                richTexts = announcementRepository.findByCreatedBy(username,pageable);
            } else {
                richTexts = announcementRepository.findByTypeAndCreatedBy(type,username,pageable);
            }
        }
        if (null == richTexts && richTexts.getSize() <= 0) {
            return richTexts;
        } else {
            //去除大字段
            richTexts.getContent().forEach(richText -> {
                richText.setContent("");
            });
        }
        return richTexts;
    }

    @Override
    @Transactional(readOnly = true)
    public Page<Announcement> findByTypeAndStatus(String type, int status, Pageable pageable) {
        return this.announcementRepository.findByTypeAndStatus(type, status, pageable);
    }

    /**
     *  获取数据库最大的排序值
     * @return
     */
    private Integer queryMaxOrderField(String type) {
        return this.announcementRepository.queryMaxOrderField(type);
    }

    @Override
    public Announcement roofPlacement(Announcement model){
        model.setOrderField(queryMaxOrderField(model.getType())+1);
        return announcementRepository.save(model);
    }
}
